package ez

import (
	"bytes"
	"encoding/json"
	"net/http"
)

type Output struct {
	Response http.ResponseWriter
	Writer   *bytes.Buffer
	Body     []byte
}

func (this *Output) Json(data interface{}) {
	tmp, e := json.Marshal(data)
	this.Body = tmp
	if e != nil {
		this.Html(e.Error())
	} else {
		_, e := this.Writer.Write(tmp)
		if e != nil {
			this.Html(e.Error())
		} else {
			//this.Response.WriteHeader(200)
			this.Response.Header().Set("Content-Type", "application/json")
		}
	}
}
func (this *Output) Html(data string) {
	_, e := this.Writer.Write([]byte(data))
	if e != nil {
		this.Html(e.Error())
	} else {
		this.Response.WriteHeader(200)
	}
}
func (this *Output) Byte(data []byte) {
	_, e := this.Writer.Write(data)
	if e != nil {
		this.Html(e.Error())
	} else {
		this.Response.WriteHeader(200)
	}
}

type JsonOut struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

func NewJsonOut(session *Session, code int, message string, data interface{}) *JsonOut {
	out := &JsonOut{
		Code:    code,
		Message: message,
		Data:    data,
	}
	session.JsonOut(out)
	return out
}
